from ._base import BaseModel
from ..extends.flask_sqlalchemy import db
from flask_login import current_user
from flask import current_app, request
try:
    from urlparse import urljoin
except ImportError:
    from urllib.parse import urljoin


class Picture(BaseModel):
    title = db.Column(db.String(80), nullable=False, default='', comment='图片标题')
    flag = db.Column(db.String(80), nullable=False, default='', comment='图片唯一标识')
    src = db.Column(db.String(200), nullable=False, comment='图片链接地址')
    # 图片存储方式  local 本地存储 oss 阿里云oss存储 等等
    power = db.Column(db.String(200), nullable=False, comment='图片驱动')
    user_id = db.Column(db.Integer, nullable=False, comment='发布人')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user_id = current_user.id
        self.power = current_app.config.get('STORAGE_PROVIDER_DEFAULT')

    @property
    def url(self):
        if self.power == 'local':
            return urljoin(request.host_url, self.src)
        return self.src
